import { _decorator, Camera, CCFloat, Component, EventTouch, geometry, Input, input, Node, PhysicsSystem, v2, v3, Vec2, Vec3, view } from 'cc';
import WorldManager from './WorldManager';
const { ccclass, property } = _decorator;

@ccclass('CameraController')
export class CameraController extends Component {
    @property(CCFloat)
    public speed:number = 1;

    private camera:Camera
    start() {
        this.camera = this.node.getComponent(Camera)
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    onTouchMove(event: EventTouch){
        
        let pre = event.getPreviousLocation()
        let now = v2(event.getLocationX(), event.getLocationY())
        let offset = v2(0,0)
        Vec2.subtract(offset, now, pre)
        this.node.translate(v3(- offset.x * this.speed, -offset.y * this.speed, offset.y * this.speed))
      
    }
    onTouchEnd(event: EventTouch){
        this.checkBorder()
    }


    public checkBorder(){
        

        let size = view.getVisibleSize()
        let width = size.width
        let height = size.height
        // 屏幕左下角发射射线
        let leftDown = this.handleRay(0, 0)
        // 屏幕右下角发射射线
        let rightDown = this.handleRay(width, 0)
        // 屏幕右上角发射射线
        let rightUp = this.handleRay(width, height)
        // 屏幕左上角发射射线
        let leftUp = this.handleRay(0, height)
        console.log(leftDown,rightDown,  rightUp, leftUp)

        WorldManager.instance.createBorder(leftDown,rightDown,  rightUp, leftUp)
     }
 
     handleRay(x: number, y: number) {
         let _ray: geometry.Ray = new geometry.Ray();
 
         this.camera.screenPointToRay(x, y, _ray);
         return PhysicsSystem.instance.raycastClosest(_ray)
         
     }
}


